﻿using SuporeSliplampApp.Base;
using SuporeSliplampApp.Util;
using SuporeSliplampApp.ViewModels;
using System;
using System.Windows;
using System.Windows.Input;
using FellowOakDicom;
using FellowOakDicom.Network.Client;
using FellowOakDicom.Network;
using System.Threading.Tasks;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// EditPortWindow.xaml 的交互逻辑
    /// </summary>
    public partial class EditPortWindow : Window
    {
        //将输入的ip和端口号传到首画面的委托
        public delegate void GetIpInfoHandler(string ipStr);
        public GetIpInfoHandler getIpInfo;
        public Action<string> action;

        public EditPortWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        //调用委托
        private void sendData()
        {
            this.action?.Invoke(IpStr.Text.ToString().Trim() + ":" + PortStr.Text.ToString().Trim());
        }

        private async void ConfirmBtn_Click(object sender, RoutedEventArgs e)
        {
            string ip = IpStr.Text.Trim();
            int port = int.Parse(PortStr.Text.Trim());

            var currentClient = DicomConnectionManager.Instance.GetClient();
            if (currentClient != null)
            {
                MessageBox.Show($"已经连接到 {ip}:{port} 的服务器！");
                return;
            }

            bool isConnected = await DicomConnectionManager.Instance.Connect(ip, port);
            if (isConnected)
            {
                // 测试服务器的响应能力，发送C-ECHO请求
                var dicomClient = DicomConnectionManager.Instance.GetClient();
                var echoRequest = new DicomCEchoRequest();
                echoRequest.OnResponseReceived += (req, response) =>
                {
                    if (response.Status == DicomStatus.Success)
                    {
                        MessageBox.Show("连接成功！可以正常通信。");
                    }
                    else
                    {
                        MessageBox.Show("连接成功，但服务器未能正确响应C-ECHO请求。");
                    }
                };

                await dicomClient.AddRequestAsync(echoRequest);
                await dicomClient.SendAsync();

                //this.Close();
            }
            else
            {
                MessageBox.Show("连接失败，请检查IP和端口号。");
            }
        }

        private async void TestBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var testClient = DicomClientFactory.Create(IpStr.Text.Trim(), int.Parse(PortStr.Text.Trim()), false, "SCU", "ORTHANC");
                var request = new DicomCEchoRequest();

                // 添加响应事件处理程序
                request.OnResponseReceived += (req, response) =>
                {
                    if (response.Status == DicomStatus.Success)
                    {
                        MessageBox.Show("测试连接成功！");
                    }
                    else
                    {
                        MessageBox.Show($"测试连接失败: {response.Status.Description}");
                    }
                };

                await testClient.AddRequestAsync(request);
                await testClient.SendAsync();

                testClient = null;

            }
            catch (Exception ex)
            {
                MessageBox.Show($"测试连接失败: {ex.Message}");
            }
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Keyboard.ClearFocus();
        }
    }

    public class DicomConnectionManager
    {
        private static DicomConnectionManager _instance;
        private IDicomClient _dicomClient;

        private DicomConnectionManager() { }

        public static DicomConnectionManager Instance => _instance ?? (_instance = new DicomConnectionManager());

        public async Task<bool> Connect(string ip, int port)
        {
            try
            {
                _dicomClient = DicomClientFactory.Create(ip, port, false, "SCU", "ORTHANC");
                var request = new DicomCEchoRequest();
                await _dicomClient.AddRequestAsync(request);
                await _dicomClient.SendAsync();
                return true;
            }
            catch
            {
                _dicomClient = null;
                return false;
            }
        }

        public IDicomClient GetClient()
        {
            return _dicomClient;
        }

        public void Disconnect()
        {
            if (_dicomClient != null)
            {
                _dicomClient = null; 
            }
        }
    }
}
